#include "database.hpp"
#include "util.hpp"
#include "httplib.h"

namespace service
{
#define WWWROOT "./www" // 定义根目录路径
#define VIDEO_ROOT "/video/"
#define IMAGE_ROOT "/image/"
    // #define VIDEO_ROOT "./www/video/" // 定义video资源路径 #define VIDEO_ROOT "/video/"
    // #define IMAGE_ROOT "./www/image/" // 定义image资源路径 #define IMAGE_ROOT "/image/"

    // 因为httplib基于多线程，因此数据管理对象需要在多线程中访问，为了便于访问定义全局变量
    data::TableVideo *tb_video = NULL;

    class Server
    {
    private:
        int _port;
        httplib::Server _srv;

    public:
        Server(int port) : _port(port) {}
        bool RunModule()
        {
            // 1.初始化操作-----初始化数据管理模块，创建指定的目录
            tb_video = new data::TableVideo();
            util::FileUtil(WWWROOT).CreateDirectory();
            std::string root = WWWROOT;
            std::string video_real_path = root + VIDEO_ROOT; // ./www/video/
            // std::string video_real_path = VIDEO_ROOT;
            util::FileUtil(video_real_path).CreateDirectory();
            std::string image_real_path = root + IMAGE_ROOT; // ./www/image/
            // std::string image_real_path = IMAGE_ROOT;
            util::FileUtil(image_real_path).CreateDirectory();

            // 2.搭建http服务器，并开始运行
            // a.设置静态资源根目录
            _srv.set_mount_point("/", WWWROOT);

            // b.添加请求与处理函数映射关系
            _srv.Post("/video", Insert);
            _srv.Delete("/video/(\\d+)", Delete);
            _srv.Put("/video/(\\d+)", Update);
            _srv.Get("/video/(\\d+)", SelectOne);
            _srv.Get("/videos", SelectAll);
            //_srv.Get("/video", SelectAll);//有问题！！！
            // 就这有这个接口的请求  是  get  /video  请求
            // 默认请求 wwwroot/video这个静态资源 请求不到   其它的请求

            // c.启动服务器
            _srv.listen("0.0.0.0", _port);

            return true;
        }

    private:
        // 新增视频请求
        static void Insert(const httplib::Request &req, httplib::Response &rsp)
        {
            if (req.has_file("name") == false ||
                req.has_file("info") == false ||
                req.has_file("video") == false ||
                req.has_file("image") == false)
            {

                rsp.status = 400;
                rsp.body = R"({"result":false, "reason":"上传的数据信息错误"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }
            httplib::MultipartFormData name = req.get_file_value("name");   // 视频名称
            httplib::MultipartFormData info = req.get_file_value("info");   // 视频简介
            httplib::MultipartFormData video = req.get_file_value("video"); // 视频文件
            httplib::MultipartFormData image = req.get_file_value("image"); // 图片文件

            // MultipartFormData{name,content_type,filename,content}
            std::string video_name = name.content;
            std::string video_info = info.content;
            // 拼接地址    //+video_name为了去重
            std::string root = WWWROOT;
            std::string video_path = root + VIDEO_ROOT + video_name + video.filename;
            std::string image_path = root + IMAGE_ROOT + video_name + image.filename;

            // 数据存储
            if (util::FileUtil(video_path).SetContent(video.content) == false) // 视频数据存储
            {
                rsp.status = 500;
                rsp.body = R"({"result":false, "reason":"视频文件存储失败"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }
            if (util::FileUtil(image_path).SetContent(image.content) == false) // 图片数据存储
            {
                rsp.status = 500;
                rsp.body = R"({"result":false, "reason":"图片文件存储失败"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }

            // Json序列化存储数据
            Json::Value video_json;
            video_json["name"] = video_name;
            video_json["info"] = video_info;
            video_json["video"] = VIDEO_ROOT + video_name + video.filename;
            video_json["image"] = IMAGE_ROOT + video_name + image.filename;

            // 数据库数据的新增
            if (tb_video->Insert(video_json) == false)
            {
                rsp.status = 500;
                rsp.body = R"({"result":false, "reason":"数据库新增数据失败"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }
            rsp.set_redirect("/index.html", 303);
            return;
        }

        // 删除视频请求
        static void Delete(const httplib::Request &req, httplib::Response &rsp)
        {
            // 1.获取要删除的视频ID
            int video_id = std::stoi(req.matches[1]);

            // 2.删除视频文件及封面图片文件
            Json::Value video;
            if (tb_video->SelectOne(video_id, &video) == false) // 判断删除文件是否存在
            {
                rsp.status = 500;
                rsp.body = R"({"result":false, "reason":"数据库不存在视频信息"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }
            std::string root = WWWROOT;
            std::string video_path = root + video["video"].asString();
            std::string image_path = root + video["image"].asString();
            remove(video_path.c_str());
            remove(image_path.c_str());

            // 3.删除数据库信息
            if (tb_video->Delete(video_id) == false)
            {
                rsp.status = 500;
                rsp.body = R"({"result":false, "reason":"数据库删除失败"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }
            return;
        }

        // 更新视频请求
        static void Update(const httplib::Request &req, httplib::Response &rsp)
        {
            // 1.获取要修改视频的信息  a. 视频id b. 修改后的信息
            int video_id = std::stoi(req.matches[1]);
            Json::Value video;
            if (util::JsonUtil::UnSerialize(req.body, &video) == false)
            {
                rsp.status = 400;
                rsp.body = R"({"result":false, "reason":"新的视频信息格式解析失败"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }

            // 2.修改数据库数据
            if (tb_video->Update(video_id, video) == false)
            {
                rsp.status = 500;
                rsp.body = R"({"result":false, "reason":"修改数据库数据失败"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }

            return;
        }

        // 查询某个视频请求
        static void SelectOne(const httplib::Request &req, httplib::Response &rsp)
        {
            // 1.获取视频ID
            int video_id = std::stoi(req.matches[1]);

            // 2.在数据库中查询指定的视频信息
            Json::Value video;
            if (tb_video->SelectOne(video_id, &video) == false)
            {
                rsp.status = 500;
                rsp.body = R"({"result":false, "reason":"查询数据库指定视频信息失败"})";
                rsp.set_header("Content-Type", "application/json");
                return;
            }

            // 3.组织响应正文-----Json格式的字符串
            util::JsonUtil::Serialize(video, &rsp.body);
            rsp.set_header("Content-type", "application/json");
            return;
        }

        // 查询所有视频请求
        static void SelectAll(const httplib::Request &req, httplib::Response &rsp)
        {
            // 两种查询方式
            //  /video   &    /video?search="关键字"
            bool select_flag = true; // 默认所有查询
            std::string search_key;
            if (req.has_param("search") == true) // 判断请求是否存在search请求
            {
                select_flag = false;                        // 模糊匹配
                search_key = req.get_param_value("search"); // httplib提供接口,获取search的关键字
            }
            Json::Value videos;
            if (select_flag == true)
            {
                if (tb_video->SelectAll(&videos) == false)
                {
                    rsp.status = 500;
                    rsp.body = R"({"result":false, "reason":"查询数据库全部视频信息失败"})";
                    rsp.set_header("Content-Type", "application/json");
                    return;
                }
            }
            else
            {
                if (tb_video->SelectLike(search_key, &videos) == false)
                {
                    rsp.status = 500;
                    rsp.body = R"({"result":false, "reason":"查询数据库匹配视频信息失败"})";
                    rsp.set_header("Content-Type", "application/json");
                    return;
                }
            }
            util::JsonUtil::Serialize(videos, &rsp.body);
            rsp.set_header("Content-type", "application/json");
            return;
        }
    };
}
